import tkinter as tk
from tools import *
from PIL import Image, ImageTk
# from PIL import ImageTk
"""图片，可调整尺寸
安装：pip install Pillow
注意：“PIL”必须在后面引入，否则报以下错误
    AttributeError: type object 'Image' has no attribute 'open'
"""
class SysImage():
    def __init__(self):
        self.tools    = Tools()

    def load(self, win, filename, give_msg = False):
        """加载图片
        """
        if len(filename) == 0: return False

        self.master = win
        self.image_path = filename
        try:
            self.image = Image.open(filename)
            # image = Image.open("D:\\py\\python-common-form\\src\\bg.jpg")
            ret = ImageTk.PhotoImage(self.image) # 将图片转换为Tkinter可以使用的格式
        except FileNotFoundError as e:
            print(f"{__name__} Error: {e};filename:{filename};")
            if give_msg: self.tools.msg(f"加载图片【{filename}】错误:{e}", 'error')
            return False
        
        self.tk_image = ImageTk.PhotoImage(self.image)
        self.canvas = tk.Canvas(win, width=self.image.width, height=self.image.height)
        self.canvas.pack()
        self.image_id = self.canvas.create_image(0, 0, anchor='nw', image=self.tk_image)

        return True
    
    def resize(self, width, height):
        """调整尺寸
        """
        # self.image = self.image.resize((width, height), Image.ANTIALIAS)
        self.image = self.image.resize((width, height))
        self.tk_image = ImageTk.PhotoImage(self.image)
        self.canvas.itemconfig(self.image_id, image=self.tk_image)
        self.canvas.config(width=width, height=height)
